package com.common.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.apache.commons.io.FilenameUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author Tsing
 * 图片上传工具
 */
public class ImageUpload {
    //OSS域名地址
    private static final String ALI_OSS="https://com-tsing.oss-cn-hangzhou.aliyuncs.com/";
    //OSS仓库名称
    private static  final String RESP_NAME = "com-tsing";
    //配置OSS对象
    //阿里云地域节点
    private static String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
    private static String accessKeyId = "LTAI5tC2iufAjhLnJdKS9rSZ";
    private static String accessKeySecret = "HeApkAYhSxxuDorFph8z4gbiFX4Igd";

    /**
     * 采取多例模式生成OSS连接对象
     * 使用@Scope("prototype)即可
     * */
    @Bean
    @Scope("prototype")
    private static OSS ossClient(){
        return new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
    }

    /**
     *图片上传方法(单张图片)
     * @return String 文件访问地址
     * */
    public static String UploadImg(MultipartFile file) throws IOException {
//        OSS oss = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
        //获得文件原名称
        String originalFilename = file.getOriginalFilename();
        //获得文件后缀
        String ex = "."+ FilenameUtils.getExtension(originalFilename);
        //使用UUID随机拼接新名称
        String uuid = UUID.randomUUID().toString();
        String fileName =  uuid + ex;
        //OSS存储文件
        ossClient().putObject(
                RESP_NAME,//OSS仓库名称
                fileName,//文件名称
                file.getInputStream()//文件输入流
        );
        ossClient().shutdown();
        return ALI_OSS+fileName;//返回最终图片地址

    }

    /**
     * 图片上传方法(多张图片) 适用于MarkDown文本内容的图片上传
     * 接收文件数组 返回地址路径集合
     * @return Map<String,String></>
     * */

    public static List<String> UploadImgs(MultipartFile[] files) throws IOException{
        List<String> imgAddress = new ArrayList<>();
        for (int i = 0; i < files.length; i++) {
            String originalFilename = files[i].getOriginalFilename();
            String extension ="." + FilenameUtils.getExtension(originalFilename);
            String uuid = UUID.randomUUID().toString();
            String fileName = uuid + extension;
            ossClient().putObject(
                    RESP_NAME,
                    fileName,
                    files[i].getInputStream()
            );
            imgAddress.add(ALI_OSS+fileName);
        }
        ossClient().shutdown();
        return imgAddress;

    }
}
